package com.adtech.farmProducts.base;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.FileUtil;
import com.adtech.common.widgets.load.core.LoadManager;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.model.UserInfo;
import com.adtech.farmProducts.model.VersionUpdate;
import com.adtech.farmProducts.widget.EmptyView;
import com.adtech.farmProducts.widget.ErrorView;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.vise.log.ViseLog;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * BaseActivity基类的定义
 */

public abstract class BaseActivity extends Activity  implements EasyPermissions.PermissionCallbacks{

    // 定义标题栏对象
    protected Toolbar mToolbar;


    @Override
    protected void initWidgets() {
        super.initWidgets();
        // 初始化标题栏对象
        initToolbar((Toolbar) findViewById(R.id.toolbar), findViewById(R.id.top_view));
    }

    /**
     * 初始化Toolbar标题栏
     *
     * @param toolbar Toolbar
     */
    public void initToolbar(Toolbar toolbar, View top_view) {
        mToolbar = toolbar;
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        if (top_view != null) {
            ImmersionBar.setTitleBar(this, top_view);
        }
        initTitleNeedBack();
    }

    /**
     * 设置Toolbar标题栏的显示属性
     */
    protected void initTitleNeedBack() {
        // 设置左上角的返回按钮为实际的返回效果
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // 设置显示返回按钮
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            // 设置不显示标题栏的title
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    public <T> RspModel<T> getAnalysis(AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(getClass().getSimpleName() + ":" + response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    return rspModel;
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                break;
            default:
                App.getInstance().showMessage(getString(R.string.service_error));
                break;
        }
        return null;
    }

    public static String imageUrl;

    /**
     * 头像上传
     */
    public void upHeardImage(String url, final LinearLayout layout_camera) {
        imageUrl="";
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData AsyncHttpPostFormData = new AsyncHttpPostFormData();
        AsyncHttpPostFormData.addFormData("file", new File(url));
        okHttpClient.postFile(Common.Constant.API_IP + "file/uploadImg", AsyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                App.getInstance().showMessage("上传失败！");
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "图片上传");
                if (rspModel == null) {
                    App.getInstance().showMessage("上传失败！");
                    return;
                }
                if (rspModel.getCode() == 1 && rspModel.getData() != null && !"".equals(rspModel.getData())) {
                    imageUrl = rspModel.getData();
                    SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, Transition<? super Drawable> transition) {
                            layout_camera.setBackground(resource);
                        }
                    };
                    Glide.with(mContext).load(imageUrl).into(simpleTarget);
                    App.getInstance().showMessage("上传成功！");
                }else {
                    App.getInstance().showMessage("上传失败！");
                }
            }
        });
    }


    /**
     * 数据解析
     *
     * @param response 数据源
     * @param type     class
     * @param log      log
     * @param <T>      泛型
     * @return 结果
     */
    public <T> RspModel<T> getAnalysisBase(LoadManager mLoadManager, AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    switch (rspModel.getCode()) {
                        case 1:
                            mLoadManager.showSuccessView();
                            return rspModel;
                        default:
                            App.getInstance().showMessage(rspModel.getMessage());
                            mLoadManager.showStateView(EmptyView.class);
                            break;
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mLoadManager.showStateView(ErrorView.class);
                }
                break;
            default:
                mLoadManager.showStateView(EmptyView.class);
                break;
        }
        return null;
    }

    /**
     * 版本更新
     */
    public void getUpdateVersion() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.post(Common.Constant.API_IP + "appVersion/lastVersion", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<VersionUpdate>>() {
                }.getType();
                RspModel<VersionUpdate> rspModel = getAnalysis(response, type, "版本更新");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        try {
                            int versionCode = getVersionCode();
                            if (rspModel.getData().getVersion() > versionCode) {
                                updateVersion(rspModel.getData().getIs_forced(), "是否更新?", rspModel.getData().getDescription(), rspModel.getData().getApk_url());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        });
    }

    private void updateVersion(int force, String title, String content, String url) {
        DownloadBuilder downloadBuilder = AllenVersionChecker.getInstance().downloadOnly(
                UIData.create().setTitle(title).setContent(content).setDownloadUrl(url)
        );
        downloadBuilder.setSilentDownload(false); //默认false
        downloadBuilder.setForceRedownload(true); //默认false 本地有安装包缓存也会重新下载apk
        downloadBuilder.executeMission(mContext);
        //强制更新
        if (force == 1) {
            //是否显示下载对话框
            downloadBuilder.setShowDownloadingDialog(true);// 默认true
            downloadBuilder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                }
            });
        } else {
            downloadBuilder.setShowDownloadingDialog(false);// 默认true
        }
    }

    /**
     * 拨打电话的操作，并关闭当前dialog
     */
    public void callPhone(String tel) {
        if (TextUtils.isEmpty(tel)) {
            UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
            if (info != null) {
                tel = info.getSiguan_phone();
            }
        }
        // 跳转到拨号界面，同时传递电话号码
        if (!TextUtils.isEmpty(tel)) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
            startActivity(intent);
        }
    }

    public void checkAndRequestPermission() {
        // 如果具有相关权限
        if (EasyPermissions.hasPermissions(mContext, mCameraPerms)) {
            // 更新头像
            camera();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this,
                    "更新头像需要授权手机的相机等相关权限",
                    PERMISSION_REQUEST_CODE,
                    mCameraPerms);
        }
    }

    /**
     * 重写权限请求的方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 把权限申请的执行结果的操作给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    /**
     * 申请权限成功
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 如果权限申请成功
        if (EasyPermissions.hasPermissions(mContext, mCameraPerms)) {
            camera();
        }
    }

    /**
     * 申请权限失败
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //处理权限名字字符串
        StringBuilder sb = new StringBuilder();
        for (String str : perms) {
            sb.append("(");
            sb.append(str);
            sb.append(")");
            sb.append("\n");
        }
        String message = sb.append("\n").toString();

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("提示")
                    .setRationale("获取图片需要以下权限：" + message + "是否打开设置界面进行授权？")
                    .setPositiveButton("是")
                    .setNegativeButton("否")
                    .build()
                    .show();
        }
    }

    public static final int PERMISSION_REQUEST_CODE = 1;
    // 定义相关权限
    public String[] mCameraPerms = new String[]{
            Manifest.permission.CAMERA//, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };


    // 定义拍照和相册裁剪操作的请求码
    public static final int CAMERA_REQUEST_CODE = 5000;
    public static final int GALLERY_REQUEST_CODE = 5001;
    public static final int CROP_REQUEST_CODE = 5002;

    // Android7.0 以上系统图片的Uri地址
    public static Uri providerUri;

    // Android7.0 以下系统图片的Uri地址
    public static Uri mUri;

    /**
     * 拍照片
     */
    public void camera() {
        //使用当前系统的日期加以调整作为照片的名称
        Date date = new Date(System.currentTimeMillis());
        //创建日期格式转换对象
        SimpleDateFormat dataFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss", Locale.getDefault());
        SimpleDateFormat.getDateInstance();
        // 定义Image图片的文件名
        String imageFileName = dataFormat.format(date) + ".jpg";
        // 获取储存头像图片文件夹的路径
        String portraitDirName = FileUtil.createAppFoldersRootPath() + File.separator + "Pictures";

        File imageFile = new File(portraitDirName, imageFileName);
        // 如果储存图片文件的目录没有创建则进行创建的操作
        if (!imageFile.getParentFile().exists()) {
            if (!imageFile.getParentFile().mkdirs()) {
                App.getInstance().showMessage(getResources().getString(R.string.toast_none));
            }
        }
        // 创建一个打开相机的意图
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Android7.0 以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            providerUri = FileProvider.getUriForFile(mContext, "com.adtech.farmProducts.fileprovider", imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, providerUri);
            // 添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            mUri = Uri.fromFile(imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        }
        // 启动相机
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    /**
     * 跳转到相册
     */
    private void gallery() {
        // 创建意图对象
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }

    /**
     * 使用uCrop进行原图片的裁剪
     *
     * @param uri Uri
     */
    public void cropRawPhoto(Uri uri) {
        // 配置裁剪的相关属性
        UCrop.Options options = new UCrop.Options();
        // 修改标题栏颜色
        options.setToolbarColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
        // 设置标题文字
        options.setToolbarTitle("裁剪图片");
        // 隐藏底部工具
        options.setHideBottomControls(false);
        // 设置图片格式
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        // 设置图片压缩质量
        options.setCompressionQuality(100);
        // 是否让用户调整范围(默认false)，如果开启，可能会造成剪切的图片的长宽比不是设定的
        // 如果不开启，用户不能拖动选框，只能缩放图片
        options.setFreeStyleCropEnabled(true);
        // 设置裁剪窗口是否为椭圆
        options.setCircleDimmedLayer(false);
        // 显示网格线
        options.setShowCropGrid(true);
        //设置是否展示矩形裁剪框
        options.setShowCropFrame(true);
        //设置裁剪框横竖线的宽度
        //        options.setCropGridStrokeWidth(4);
        //设置裁剪框横竖线的颜色
        //        options.setCropGridColor(Color.YELLOW);
        //设置竖线的数量
        options.setCropGridColumnCount(2);
        //设置横线的数量
        options.setCropGridRowCount(2);

        //使用当前系统的日期加以调整作为照片的名称
        Date date = new Date(System.currentTimeMillis());
        //创建日期格式转换对象
        SimpleDateFormat dataFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss", Locale.getDefault());
        // 定义Image图片的文件名
        String imageFileName = dataFormat.format(date) + ".png";
        // 获取储存头像图片文件夹的路径
        String portraitDirName = FileUtil.createAppFoldersRootPath() + File.separator + "Pictures";
        File portraitFile = new File(portraitDirName);
        if (!portraitFile.exists()) {
            if (!portraitFile.mkdirs()) {
                App.getInstance().showMessage(getResources().getString(R.string.toast_none));
            }
        }
        // 设置源Uri以及目标Uri
        UCrop.of(uri, Uri.fromFile(new File(portraitDirName, imageFileName)))
                // 设置长宽比
                .withAspectRatio(1, 1)
                // 设置图片的长度和宽度
                .withMaxResultSize(200, 200)
                // 加载配置属性
                .withOptions(options)
                .start(this, CROP_REQUEST_CODE);
    }
}
